<template>
    <div class="user">
        <Tabs type="card" v-model:value="currentTab" @on-click="choose">
            <TabPane icon="ios-list-box-outline" label="用户列表" name="userList">
                <div class="userList">
                    <!--查询条件-->
                    <div class="header">

                    </div>
                    <!--表格-->
                    <div class="body">
                        <Table :columns="userListData"
                               :data="userList"
                               show-header
                               draggable
                               border
                               size="small"
                               @on-drag-drop="dragOrder"
                               @on-selection-change="selectMany">

                            <!--账户名-->
                            <template slot-scope="{ row, index }" slot="accountName">
                                <span @click="goDetails(row,index)">{{row.userName}}</span>
                            </template>

                            <!--登录账号-->
                            <template slot-scope="{ row, index }" slot="account">
                                <span>{{row.iphoneNo}}</span>
                            </template>

                            <!--角色-->
                            <template slot-scope="{ row, index }" slot="role">
                                <span v-for="(obj,i) in row.sysRoles">
                                    <Tooltip :content="obj.roleDesc" theme="light">
                                        <span class="t-role">{{obj.roleName}}</span>
                                    </Tooltip>
                                </span>
                            </template>

                            <!--详情-->
                            <template slot-scope="{ row, index }" slot="details">
                                <Button size="small" type="success" @click="goDetails(row, index)">详情</Button>
                            </template>

                            <!--操作-->
                            <template slot-scope="{ row, index }" slot="handle">
                                <Button size="small" type="info" @click="edit(row, index)">编辑</Button>
                            </template>

                            <!--排序-->
                            <template slot-scope="{ row, index }" slot="order">
                                <Button size="small" type="warning" @click="order(row, index)">排序</Button>
                            </template>

                            <!--删除-->
                            <template slot-scope="{ row, index }" slot="del">
                                <Button size="small" type="error" @click="del(row, index)">删除</Button>
                            </template>
                        </Table>
                    </div>
                </div>
            </TabPane>
            <TabPane icon="ios-add-circle-outline" label="新增用户" name="userAdd">
                <Form :model="userInfo" :label-width="100">
                    <FormItem label="用户名">
                        <Tooltip content="1-14个字符" placement="right" theme="light">
                            <Input prefix="ios-contact-outline"
                                   v-model="userInfo.userName"
                                   placeholder="用户名"
                                   style="width: 500px"
                                   clearable/>
                        </Tooltip>
                    </FormItem>

                    <FormItem label="手机号">
                        <Input prefix="md-tablet-portrait"
                               v-model="userInfo.iphoneNo"
                               placeholder="手机号"
                               style="width: 500px"
                               clearable/>
                    </FormItem>

                    <FormItem label="密码">
                        <Tooltip placement="right" theme="light">
                            <div slot="content">
                                <p>6~14个字符，区分大小写</p>
                                <p><i>字母，数字，标点符号(除空格)</i></p>
                            </div>
                            <Input prefix="ios-finger-print"
                                   v-model="userInfo.pwd"
                                   placeholder="密码"
                                   style="width: 500px"
                                   clearable/>
                        </Tooltip>
                    </FormItem>

                    <FormItem label="角色">
                        <CheckboxGroup v-model="userInfo.sysRoles">
                            <div v-for="(obj,i) in sysRole">
                                <Checkbox :label="obj.roleId">
                                    <div class="roleName">
                                        {{obj.roleName}}
                                    </div>
                                    <div class="roleDesc">
                                        {{obj.roleDesc}}
                                    </div>
                                </Checkbox>
                            </div>
                        </CheckboxGroup>
                    </FormItem>

                    <FormItem>
                        <Button type="primary" v-if="addUserBtnFlag" @click="insertUser">新增用户</Button>
                        <Button v-if="!addUserBtnFlag">新增用户</Button>
                    </FormItem>
                </Form>
            </TabPane>
        </Tabs>

        <!--用户详细信息-->
        <Modal v-model="userDetailsFlag"
               draggable
               width="800">
            <p slot="header">
                <span style="color: #FF0000;font-size: 18px">用户信息</span>
            </p>

            <Form :model="userInfo" :label-width="100">
                <FormItem label="用户名">
                    <Input prefix="ios-contact-outline"
                           v-model="userInfo.userName"
                           disabled
                           style="width: 300px"/>
                </FormItem>

                <FormItem label="手机号">
                    <Input prefix="md-tablet-portrait"
                           v-model="userInfo.iphoneNo"
                           disabled
                           style="width: 300px"/>
                </FormItem>

                <FormItem label="密码">
                    <Input type="password"
                           prefix="ios-finger-print"
                           value="******"
                           disabled
                           style="width: 300px"/>
                </FormItem>

                <FormItem label="角色">
                    <CheckboxGroup v-model="sysRoleIds">
                        <div v-for="(obj,i) in sysRole">
                            <Checkbox :label="obj.roleId" disabled>
                                <div class="roleName">
                                    {{obj.roleName}}
                                </div>
                                <div class="roleDesc">
                                    {{obj.roleDesc}}
                                </div>
                            </Checkbox>
                        </div>
                    </CheckboxGroup>
                </FormItem>
            </Form>
        </Modal>

        <!--用户更新信息-->
        <Modal v-model="userUpdateFlag"
               draggable
               width="800"
               @on-ok="okUpdateUser"
               @on-cancel="">
            <p slot="header">
                <span style="color: #FF0000;font-size: 18px">用户更新</span>
            </p>

            <Form :model="userInfo" :label-width="100">
                <FormItem label="用户名">
                    <Tooltip content="1-14个字符" placement="right" theme="light">
                        <Input prefix="ios-contact-outline"
                               v-model="userInfo.userName"
                               placeholder="用户名"
                               style="width: 500px"
                               clearable/>
                    </Tooltip>
                </FormItem>

                <FormItem label="手机号">
                    <Input prefix="md-tablet-portrait"
                           v-model="userInfo.iphoneNo"
                           style="width: 500px"
                           clearable/>
                </FormItem>

                <FormItem label="密码">
                    <Tooltip placement="right" theme="light">
                        <div slot="content">
                            <p>6~14个字符，区分大小写</p>
                            <p><i>字母，数字，标点符号(除空格)</i></p>
                        </div>
                        <Input prefix="ios-finger-print"
                               v-model="userInfo.pwd"
                               placeholder="密码"
                               style="width: 500px"
                               clearable/>
                    </Tooltip>
                </FormItem>

                <FormItem label="角色">
                    <CheckboxGroup v-model="sysRoleIds">
                        <div v-for="(obj,i) in sysRole">
                            <Checkbox :label="obj.roleId">
                                <div class="roleName">
                                    {{obj.roleName}}
                                </div>
                                <div class="roleDesc">
                                    {{obj.roleDesc}}
                                </div>
                            </Checkbox>
                        </div>
                    </CheckboxGroup>
                </FormItem>
            </Form>
        </Modal>

        <!--删除询问面板-->
        <Modal v-model="userDelFlag"
               draggable
               @on-ok="okUserDel"
               @on-cancel="cancelUserDel">
            <p slot="header">
                <span style="color: #FF0000;font-size: 18px">用户删除</span>
            </p>

            <p>
                确定删除
                <span style="color: #FF0000;font-size: 16px;margin: 0px 8px">{{row.userName}}</span>
                的用户吗?
            </p>
            <span style="color: #FF0000;font-size: 14px">【慎重删除，删除无法找回】</span>
        </Modal>

        <!--排序面板-->
        <Modal v-model="orderFlag"
               draggable
               @on-ok="okUserOrder">
            <p slot="header">
                <span style="color: #FF0000;font-size: 18px">用户排序</span>
            </p>

            将该用户
            <span style="color: #FF0000;font-size: 16px;margin: 0px 8px">{{userInfo.userName}} </span>
            放置序号为
            <InputNumber :max="userList.length"
                         :min="1"
                         style="width: 100px;margin: 0px 8px"
                         v-model="tmpIndex"></InputNumber>
            的用户前
        </Modal>
    </div>
</template>

<script>
    import {checkIsNull} from "@/tools/Null";
    import {checkIphoneNo} from "@/tools/Reg";
    import * as Base64 from "js-base64";
    import {delCookie} from "@/tools/cookie";

    export default {
        name: "",
        components: {},
        data() {
            return {
                //当前标签页
                currentTab: "userList",
                //用户详情信息
                userDetailsFlag: false,
                userUpdateFlag: false,
                row: {},
                pwd: "",
                index: 0,
                //用户列表
                userList: [],
                //用户列表数据
                userListData: [
                    {type: 'selection', width: 60, align: 'center'},
                    {title: "序号", type: 'index', resizable: true, align: "center", width: 100},
                    {
                        title: "用户名",
                        slot: 'accountName',
                        key: 'accountName',
                        resizable: true,
                        align: "center",
                        width: 180
                    },
                    {title: "登录账号", slot: 'account', key: 'account', resizable: true, align: "center", width: 200},
                    {title: "角色", slot: "role", key: 'role', resizable: true, align: "left",},
                    {title: "详情", slot: 'details', resizable: true, align: "center", width: 120},
                    {title: "编辑", slot: 'handle', resizable: true, align: "center", width: 120},
                    {title: "排序", slot: 'order', resizable: true, align: "center", width: 120},
                    {title: "删除", slot: 'del', resizable: true, align: "center", width: 120}
                ],
                //用户对象
                userInfo: {
                    userId: "",
                    userName: "",
                    iphoneNo: "",
                    pwd: "",
                    po: "",
                    pc: "",
                    headUrl: "",
                    status: "",
                    createTime: "",
                    sysRoles: []
                },
                //角色
                sysRole: [],
                sysRoleIds: [],
                //用户id
                userIds: [],
                //新增用户按钮图标
                addUserBtnFlag: true,
                updateUserBtnFlag: true,
                userDelFlag: false,
                orderFlag: false,
                //放置索引
                tmpIndex: 1
            }
        },
        methods: {
            //查询用户列表
            selectUserList: function () {
                this.axios.get(`/login/sysUser/sysUserList`)
                    .then((data) => {
                        this.userList = data.data
                    })
            },
            //选中新增用户
            choose: function (name) {
                if (name == "userAdd") {
                    this.selectRoleList()
                    this.userInfo = {
                        userId: "",
                        userName: "",
                        iphoneNo: "",
                        pwd: "",
                        po: "",
                        pc: "",
                        headUrl: "",
                        status: "",
                        createTime: "",
                        sysRoles: []
                    }
                }
                if (name == "userList") {
                    this.selectUserList()
                    this.$Message.destroy();
                }
            },
            //查询角色
            selectRoleList: function () {
                this.axios.get(`/login/sysRole/sysRoleList`)
                    .then((data) => {
                        this.sysRole = data.data
                    })
            },
            //去详情页面
            goDetails: function (row, index) {
                this.userInfo = row
                this.index = index
                this.selectRoleList();
                this.userDetailsFlag = true

                for (let i = 0; i < this.userInfo.sysRoles.length; i++) {
                    this.sysRoleIds.push(this.userInfo.sysRoles[i].roleId)
                }
            },
            //编辑
            edit: function (row, index) {
                this.userInfo = row;
                this.index = index
                this.selectRoleList();
                this.userUpdateFlag = true

                for (let i = 0; i < this.userInfo.sysRoles.length; i++) {
                    this.sysRoleIds.push(this.userInfo.sysRoles[i].roleId)
                }
            },
            //多选
            selectMany: function (selection) {
            },
            //排序
            order: function (row, index) {
                this.orderFlag = true
                this.userInfo = row
                this.index = index
            },
            okUserOrder: function () {
                let number = this.tmpIndex - this.index;
                if (number == 1 || number == 2) {
                    this.$Message.error({
                        background: true,
                        closable: true,
                        duration: 2,
                        content: '请勿将本条数据原地移动'
                    });
                    return
                }
                if (this.tmpIndex > this.index) {
                    this.tmpIndex--
                }
                let tmpUserList = this.userList;
                tmpUserList.delete(this.index)
                tmpUserList.insert(this.tmpIndex, this.userInfo)

                let ids = []
                for (let i = 0; i < this.userList.length; i++) {
                    ids.push(this.userList[i].userId)
                }
                this.axios.put(`/login/sysUser/order`, ids)
                    .then((data) => {
                        this.$Message.warning({
                            background: true,
                            closable: true,
                            duration: 2,
                            content: '用户排序成功'
                        });
                    })
            },
            //拖拽排序
            dragOrder: function (fromIndex, toIndex) {
                this.userInfo = this.userList[fromIndex];
                this.index = fromIndex;
                this.tmpIndex = toIndex + 1;
                this.okUserOrder()
            },
            //删除
            del: function (row, index) {
                this.userDelFlag = true;
                this.row = row
            },
            //确定用户删除
            okUserDel: function () {
                this.axios.delete(`/login/sysUser/sysUser/${this.row.userId}`)
                    .then((data) => {
                        this.$Message.error({
                            background: true,
                            closable: true,
                            duration: 2,
                            content: '用户删除成功'
                        });
                        this.selectUserList()
                        //如果删除的用户是自己,退出
                        this.checkUserAuth(this.row.userId);
                    })
            },
            //取消用户删除
            cancelUserDel: function () {

            },
            //更新用户前校验
            checkUserBeforeUpdate: function () {
                let flag = true;
                //校验用户名
                let b = checkIsNull(this.userInfo.userName);
                if (b) {
                    this.$Message.error({
                        background: true,
                        closable: true,
                        content: '用户名不能为空'
                    });
                    flag = false
                } else {
                    if (this.userInfo.userName.length > 14) {
                        this.$Message.error({
                            background: true,
                            closable: true,
                            content: '用户名不符合规范'
                        });
                        flag = false
                    }
                }
                //校验手机号
                let b1 = checkIsNull(this.userInfo.iphoneNo);
                if (b1) {
                    this.$Message.error({
                        background: true,
                        closable: true,
                        content: '手机号不能为空'
                    });
                    flag = false
                } else {
                    let b2 = checkIphoneNo(this.userInfo.iphoneNo);
                    if (!b2) {
                        this.$Message.error({
                            background: true,
                            closable: true,
                            content: '手机号格式错误'
                        });
                        flag = false
                    }
                }
                //校验密码
                let b3 = checkIsNull(this.userInfo.pwd);
                if (!b3) {
                    let length = this.userInfo.pwd.length;
                    if (length < 6 || length > 14) {
                        this.$Message.error({
                            background: true,
                            closable: true,
                            content: '密码不符合规范'
                        });
                        flag = false
                    }
                }
                //校验角色
                if (this.sysRoleIds.length == 0) {
                    this.$Message.error({
                        background: true,
                        closable: true,
                        content: '至少分配一个角色'
                    });
                    flag = false
                }
                return flag
            },
            //更新用户
            okUpdateUser: function () {
                this.$Message.destroy();
                let b = this.checkUserBeforeUpdate();
                if (!b) {
                    return
                }
                let data = {
                    userName: this.userInfo.userName,
                    iphoneNo: this.userInfo.iphoneNo,
                    sysRoles: this.sysRoleIds
                }
                if (this.userInfo.pwd != null && this.userInfo.pwd.trim() != "") {
                    data.po = Base64.encode(this.userInfo.pwd)
                    data.pc = this.Md5(this.userInfo.pwd)
                }
                this.axios.put(`/login/sysUser/sysUser/${this.userInfo.userId}`, data)
                    .then((data) => {
                        //新增用户按钮
                        this.updateUserBtnFlag = true
                        if (data.code == 20001) {
                            this.$Message.error({
                                background: true,
                                closable: true,
                                content: '该账号已注册'
                            });
                            this.row.iphoneNo = "";
                            return false;
                        }
                        this.$Message.info({
                            background: true,
                            closable: true,
                            duration: 1,
                            content: '用户更新成功'
                        });
                        //跳转用户列表
                        this.currentTab = "userList"
                        this.selectUserList();
                        this.userInfo.userName = ""
                        this.userInfo.iphoneNo = ""
                        this.userInfo.pwd = ""
                        this.userInfo.sysRoles = []
                        this.row = {}
                        this.sysRoleIds = []
                        //如果删除的用户是自己,退出
                        this.checkUserAuth(this.userInfo.userId);
                    })
            },
            //添加用户前校验
            checkUser: function () {
                let flag = true;
                //校验用户名
                let b = checkIsNull(this.userInfo.userName);
                if (b) {
                    this.$Message.error({
                        background: true,
                        closable: true,
                        content: '用户名不能为空'
                    });
                    flag = false
                } else {
                    if (this.userInfo.userName.length > 14) {
                        this.$Message.error({
                            background: true,
                            closable: true,
                            content: '用户名不符合规范'
                        });
                        flag = false
                    }
                }
                //校验手机号
                let b1 = checkIsNull(this.userInfo.iphoneNo);
                if (b1) {
                    this.$Message.error({
                        background: true,
                        closable: true,
                        content: '手机号不能为空'
                    });
                    flag = false
                } else {
                    let b2 = checkIphoneNo(this.userInfo.iphoneNo);
                    if (!b2) {
                        this.$Message.error({
                            background: true,
                            closable: true,
                            content: '手机号格式错误'
                        });
                        flag = false
                    }
                }
                //校验密码
                let b3 = checkIsNull(this.userInfo.pwd);
                if (b) {
                    this.$Message.error({
                        background: true,
                        closable: true,
                        content: '密码不能为空'
                    });
                    flag = false
                } else {
                    let length = this.userInfo.pwd.length;
                    if (length < 6 || length > 14) {
                        this.$Message.error({
                            background: true,
                            closable: true,
                            content: '密码不符合规范'
                        });
                        flag = false
                    }
                }
                //校验角色
                if (this.userInfo.sysRoles.length == 0) {
                    this.$Message.error({
                        background: true,
                        closable: true,
                        content: '至少分配一个角色'
                    });
                    flag = false
                }
                return flag
            },
            //添加用户
            insertUser: function () {
                this.$Message.destroy();
                let b = this.checkUser();
                if (!b) {
                    return
                }
                //幂等
                this.addUserBtnFlag = false
                //发起请求
                let data = {
                    userName: this.userInfo.userName,
                    iphoneNo: this.userInfo.iphoneNo,
                    po: Base64.encode(this.userInfo.pwd),
                    pc: this.Md5(this.userInfo.pwd),
                    sysRoles: this.userInfo.sysRoles
                }
                this.axios.post(`/login/sysUser/sysUser`, data)
                    .then((data) => {
                        //新增用户按钮
                        this.addUserBtnFlag = true
                        if (data.code == 20001) {
                            this.$Message.error({
                                background: true,
                                closable: true,
                                content: '该账号已注册'
                            });
                            this.userInfo.iphoneNo = "";

                            return false;
                        }
                        //跳转用户列表
                        this.currentTab = "userList"
                        this.selectUserList();

                        this.userInfo.userName = "",
                            this.userInfo.iphoneNo = "",
                            this.userInfo.pwd = "",
                            this.userInfo.sysRoles = []
                    })
            },
            //删除和更新之后，如果是更新的本人，退出登录
            checkUserAuth: function (userId) {
                if (userId == this.currentUserId) {
                    //删除 sessionStorage
                    window.sessionStorage.clear();
                    //删除 cookie
                    delCookie("isLogin");
                    delCookie("token");
                    delCookie("userInfo");

                    //刷新页面到首页
                    this.$emit("my-event-app-login", false)
                    window.location.replace("/")
                }
            }
        },
        computed: {
            currentUserId: function () {
                return this.$store.getters.getId
            },
        },
        mounted() {
            this.selectUserList();
        }
    }
</script>

<style>
    /*用户列表*/
    .user .userList {
        margin-top: -16px;
        width: 100%;
    }

    .user .userList .body {
        margin-top: 10px;
    }

    .user .t-role {
        display: inline-block;
        background-color: #EEE;
        border-radius: 4px;
        margin: 0px 3px;
        padding: 0px 4px 0px 4px;
    }

    .user .roleName {
        display: inline-block;
        width: 150px;
    }

    /**/
    .user .roleDesc {
        display: inline-block;
    }

    .ivu-checkbox-group .roleName {
        width: 150px;
        display: inline-block;
    }

    .ivu-checkbox-group .roleDesc {
        display: inline-block;
    }
</style>